﻿using DatabaseProxy.ObjectSql;
using Microsoft.Data.SqlClient;
using System.Linq.Expressions;
using System.Text;

namespace DatabaseProxy.DatabaseProxy;
public partial class DatabaseProxyCore
{
    /// <summary>
    /// 删除所有数据
    /// </summary>
    /// <typeparam name="T">删除的数据类型</typeparam>
    /// <returns>影响行数</returns>
    public int DeleteEntity<T>() where T : IDatabaseTable
    {
        int result = 0;
        string sql = ObjectSqlDeleter<T>.Sql();
        result = ExecuteSql<int>(sql, command => command.ExecuteNonQuery());
        return result;
    }
    /// <summary>
    /// 异步删除所有数据
    /// </summary>
    /// <typeparam name="T">删除的数据类型</typeparam>
    /// <returns>影响行数</returns>
    public async Task<int> DeleteEntityAsync<T>() where T : IDatabaseTable
    {
        int result = 0;
        string sql = ObjectSqlDeleter<T>.Sql();
        result = await ExecuteSqlAsync<int>(sql, async command => await command.ExecuteNonQueryAsync());
        return result;
    }
    /// <summary>
    /// 删除数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="TK"></typeparam>
    /// <param name="entity"></param>
    /// <returns></returns>
    public int DeleteEntity<T, TK>(TK entity) where T : IDatabaseTable
    {
        var result = 0;
        using SqlConnection conn = new(ConnectionString);
        conn.Open();
        string sql = ObjectSqlDeleter<T>.Sql();
        using SqlCommand command = new(sql, conn);
        object? value = entity is T ? Tool<T>.PrimaryKeyProperty!.GetValue(entity) : entity;
        command.Parameters.Add(new SqlParameter
        {
            ParameterName = Tool<T>.PrimaryKeyProperty!.Name,
            Value = value ?? DBNull.Value
        });
        result = command.ExecuteNonQuery();
        return result;
    }
    /// <summary>
    /// 条件删除数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="expression"></param>
    /// <returns></returns>
    public int DeleteEntity<T>(Expression<Func<T, bool>> expression) where T : IDatabaseTable
    {
        using SqlConnection conn = new(ConnectionString);
        conn.Open();
        StringBuilder sqlBuilder = new($"DELETE FROM {Tool<T>.TableName} ");
        SqlVisitor visitor = new();
        visitor.Visit(expression);
        sqlBuilder.Append(visitor.GetSql());
        using SqlCommand command = new(sqlBuilder.ToString(), conn);
        int result = command.ExecuteNonQuery();
        return result;
    }
}
